package com.ph.shopping.facade.permission.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.ph.shopping.common.core.base.BaseService;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.facade.permission.vo.MenuVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.config.annotation.Service;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.facade.mapper.MenuMapper;
import com.ph.shopping.facade.mapper.RoleMapper;
import com.ph.shopping.facade.permission.entity.Role;
import com.ph.shopping.facade.permission.service.IMenuService;


@Component
@Service(version="1.0.0")
public class MenuService extends BaseService implements IMenuService{

	private static final Logger logger = LoggerFactory.getLogger(MenuService.class);
	
	@Autowired
	private MenuMapper menuMapper;
	
	@Autowired
	private RoleMapper roleMapper;

	@Override
	public Result getMenuByUserId(Long userId) {
		try {
			List<Role> list = roleMapper.getRoleByUserId(userId);
			if (CollectionUtils.isEmpty(list)) {
				return getResult(ResultEnum.NO_PERMISSION);
			}
			List<Long> role = new ArrayList<Long>();
			for (Role r : list) {
				role.add(r.getId());
			}
			List<MenuVo> menuVos = menuMapper.getMenuByRoleIdAndUserId(role);
			return getResult(ResultEnum.SUCCESS,getMenuTree(menuVos));
		} catch (Exception ex) {
			logger.error("通过用户id查询菜单异常，ex={}",ex);
		}
		return getResult(ResultEnum.INTERNAL_SERVER_ERROR);
	}

	@Override
	public Result getAllMenu() {
		return getResult(ResultEnum.SUCCESS, menuMapper.getAllMenu());
	}

	/**
	 * 获取菜单树
	 * @param menuVos
	 * @return
	 */
	public static List<MenuVo> getMenuTree(List<MenuVo> menuVos) {
		List<MenuVo> treeList = new ArrayList<MenuVo>();
		if (CollectionUtils.isNotEmpty(menuVos)) {
			for (MenuVo vo : menuVos) {
				if (null != vo.getParentId() && Long.valueOf(0).equals(vo.getParentId())) {
					vo = getChildMenu(vo,menuVos);
					treeList.add(vo);
				}
			}
		}
		return treeList;
	}

	private static MenuVo getChildMenu(MenuVo parent, List<MenuVo> menuVos) {
		List<MenuVo> child = null;
		for (MenuVo vo : menuVos) {
			if (parent.getId().equals(vo.getParentId())) {
				vo = getChildMenu(vo, menuVos);
				if (child == null) {
					child = new ArrayList<MenuVo>();
				}
				child.add(vo);
			}
		}
		parent.setChild(child);
		return parent;
	}

}
